///////////////////////////////////////////////////////////////////////////////
////  (c) Chaichuk AU (chaichuk@mail.ru), 								   ////
////  2004, Chelyabinsk, NTC Privodnaya Tehnika (momentum@chel.surnet.ru)  ////
///////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "../api.h"
#include "arc20.h"
#include "iofuncs.h"
#include "ctnet_io.h"

int
io_devctl (resmgr_context_t *ctp, io_devctl_t *msg, RESMGR_OCB_T *ocb)
{
	int					sts;
	void				*data;
	int					nbytes;
	int					dcmd;
	int					len;
	uint8_t				menu  [10];
	uint8_t				param [10];
	float				buf [10];
//	ctnet_data_t*		ctnet_data;

	arc20_t*			arc20 = & ((arc20_attr_t*)(ocb->attr))->arc20;
	
/*
 *	WARNING:  check in main.c to see if you need to adjust the "nparts_max" and "msg_max_size"
*/


	// see if it's a standard POSIX-supported devctl()
	if ((sts = iofunc_devctl_default (ctp, msg, ocb)) != _RESMGR_DEFAULT) {
		return (sts);
	}

	// assign a pointer to the data area of the message
	data = _DEVCTL_DATA (*msg);

	// get other data that can't be wiped out before we wipe the data structure
	dcmd = msg -> i.dcmd;
	len = msg -> i.nbytes;
	memset (&msg -> o, 0, sizeof (msg -> o));

	// preset the number of bytes that we'll return to zero
	nbytes = 0;

	// check for all commands
	switch (dcmd) {

	case DCMD_READ_CTNET:

//		ctnet_data 
		
		menu  [0] = 1;
		param [0] = 5;
		menu  [1] = 6;
		param [1] = 22;
		menu  [2] = 20;
		param [2] = 1;
		CTNET_param_read (arc20, 1 /*dst_ID*/, 3 /*n_param*/, menu, param, buf);
		
		printf ("buf [0] = %f\n", buf [0]);
		printf ("buf [1] = %f\n", buf [1]);
		printf ("buf [2] = %f\n", buf [2]);
		
//		hostlink_data = (hostlink_data_t *) data;
//		if (port_fd == -1) port_fd = open_port (port_name, port_speed);
//		retry_count = 0;
//		do {
//			return_code = FINS_memory_read (port_fd, 0, hostlink_data->mem_code, hostlink_data->start_addr, hostlink_data->n_elem, hostlink_data->data);
//			retry_count ++;			
//		} while (return_code < 0 && retry_count < retry_max);
//		if (return_code < 0) fprintf (stderr, "FINS read failure !!!\n");
//		hostlink_data->return_code = return_code;
//		nbytes = sizeof (hostlink_data_t);
		break;

	default:
		return (ENOSYS);
	}

	// return data (if any) to the client
	msg -> o.nbytes = nbytes;
	SETIOV (ctp -> iov, &msg -> o, sizeof (msg -> o) + nbytes);
	return (_RESMGR_NPARTS (1));
}